﻿using Android.Content;
using Android.Content.PM;
using Android.Media.Projection;
using Android.OS;
using Android.Runtime;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using Android.Provider;
using Android.Views.Accessibility;
using Android.AccessibilityServices;

namespace ScreenShotDemo
{
    /// <summary>
    /// 权限处理类
    /// </summary>
    public class PermissionHelper
    {
        public const int RequestCode = 1001;//普通权限请求码
        public const int AlertWinCode = 2001;//悬浮窗权限请求码
        public const int MediaProjectionCode = 3001;//截图权限请求码
        private readonly Activity? _activity;
        private MediaProjectionManager? _mediaProjectionManager;
        public PermissionHelper(Activity? activity)
        {
            _activity = activity;
        }

        /// <summary>
        /// 获取未授权的权限
        /// </summary>
        /// <param name="permissions"></param>
        /// <returns></returns>
        public List<string> GetUnauthorizedPermissionss(string[] permissions)
        {
            return permissions.Where(p => ContextCompat.CheckSelfPermission(_activity, p) != (int)Permission.Granted).ToList();
        }
        /// <summary>
        /// 根据权限列表请求权限
        /// </summary>
        /// <param name="permissions"></param>
        public void RequestPermissions(string[] permissions)
        {
            var needRequest = GetUnauthorizedPermissionss(permissions);
            if (needRequest.Any())
            {
                ActivityCompat.RequestPermissions(_activity, needRequest.ToArray(), RequestCode);
            }
        }
        public void RequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            List<string> permissionsList = new List<string>();
            if (requestCode == PermissionHelper.RequestCode)
            {
                for (int i = 0; i < permissions.Length; i++)
                {
                    if (grantResults[i] == Permission.Granted)
                    {
                        // 权限被授予  
                        Console.WriteLine($"权限 {permissions[i]} 开放.");
                    }
                    else
                    {
                        // 权限被拒绝  
                        Console.WriteLine($"权限 {permissions[i]} 拒绝.");
                        permissionsList.Add(permissions[i]);
                    }
                }
                if (permissionsList.Count > 0)
                {
                    RequestPermissions(permissionsList.ToArray());
                }
            }
        }
        /// <summary>  
        /// 显示权限解释弹窗  
        /// </summary>  
        /// <param name="permission"></param>  
        public void HandleDeniedPermission(string permission)
        {
            if (ActivityCompat.ShouldShowRequestPermissionRationale(_activity, permission))
                ShowRationaleDialog(permission); // 显示解释弹窗  
            else
                OpenAppSettings(); // 跳转系统设置页  
        }
        /// <summary>  
        /// 拒绝授权后将无法使用功能  
        /// </summary>  
        /// <param name="permission"></param>  
        private void ShowRationaleDialog(string permission)
        {
            var alertDialog = new AlertDialog.Builder(_activity);
            alertDialog.SetTitle("权限说明"); // 修复重复调用 SetTitle
            alertDialog.SetMessage($"{permission}被拒绝，该权限为必要权限，是否重新申请权限，否则将退出APP");// 显示权限说明
            alertDialog.SetPositiveButton("去设置", (sender, args) =>
            {
                OpenAppSettings(); // 跳转系统设置页  
            });
            alertDialog.SetNegativeButton("取消", (sender, args) =>
            {
                // 退出应用
                _activity?.FinishAffinity(); // 关闭当前Activity及其所有父Activity
            });
            alertDialog.Show(); // 显示弹窗
        }
        /// <summary>  
        /// 打开系统设置页面  
        /// </summary>  
        private void OpenAppSettings()
        {
            var intent = new Intent(Settings.ActionApplicationDetailsSettings);
            intent.SetData(Android.Net.Uri.Parse("package:" + _activity?.PackageName));
            _activity?.StartActivity(intent);
        }
        /// <summary>
        /// 请求悬浮窗权限
        /// </summary>
        public void RequestOverlayPermission()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.M && !Settings.CanDrawOverlays(_activity))
            {
                var intent = new Intent(Settings.ActionManageOverlayPermission,
                    Android.Net.Uri.Parse("package:" + _activity?.PackageName));
                _activity?.StartActivityForResult(intent, AlertWinCode); // 请求码需自定义
            }
        }
        /// <summary>
        /// 处理悬浮窗权限请求结果
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="resultCode"></param>
        /// <param name="data"></param>
        public void RequestOverlayPermissionResult(int requestCode, [GeneratedEnum] Result resultCode, Intent? data)
        {
            if (requestCode == AlertWinCode)
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M && Settings.CanDrawOverlays(_activity))
                {
                    // 权限已授予
                    Console.WriteLine("悬浮窗权限已授予");
                }
                else
                {
                    ShowSpecilRationaleDialog("悬浮窗权限被拒绝");
                }
            }
        }

        /// <summary>  
        /// 拒绝授权后将无法使用功能  
        /// </summary>  
        /// <param name="permission"></param>  
        public void ShowSpecilRationaleDialog(string permission)
        {
            var alertDialog = new AlertDialog.Builder(_activity);
            alertDialog.SetTitle("权限说明"); // 修复重复调用 SetTitle
            alertDialog.SetMessage($"{permission}，该权限为必要权限，是否重新申请权限，否则将退出APP");// 显示权限说明
            alertDialog.SetPositiveButton("去设置", (sender, args) =>
            {
                if (permission.IndexOf("悬浮窗") > -1)
                    RequestOverlayPermission(); // 跳转系统设置页
                else
                    RequestScreenCapturePermission(); // 跳转系统设置页
            });
            alertDialog.SetNegativeButton("取消", (sender, args) =>
            {
                // 退出应用
                _activity?.FinishAffinity(); // 关闭当前Activity及其所有父Activity
            });
            alertDialog.Show(); // 显示弹窗
        }

        /// <summary>
        /// 请求截图权限
        /// </summary>
        public void RequestScreenCapturePermission()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                _mediaProjectionManager = _activity?.GetSystemService(Context.MediaProjectionService) as MediaProjectionManager;
                var intent = _mediaProjectionManager?.CreateScreenCaptureIntent();
                _activity?.StartActivityForResult(intent, MediaProjectionCode);
            }
        }
        /// <summary>
        /// 处理截图权限请求结果
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="resultCode"></param>
        /// <param name="data"></param>
        public void RequestScreenCapturePermissionResult(int requestCode, [GeneratedEnum] Result resultCode, Intent? data)
        {
            if (requestCode == MediaProjectionCode)
            {
                if (resultCode == Result.Ok)
                {
                    // 截图权限已授予
                    Console.WriteLine("截图权限已授予");
                }
                else
                {
                    ShowSpecilRationaleDialog("截图权限被拒绝");
                }
            }
        }
        /// <summary>
        /// 处理特殊权限请求结果
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="resultCode"></param>
        /// <param name="data"></param>
        public void SpecialPermissionResult(int requestCode, [GeneratedEnum] Result resultCode, Intent? data)
        {
            switch (requestCode)
            {
                case PermissionHelper.AlertWinCode:
                    RequestOverlayPermissionResult(requestCode, resultCode, data);
                    break;
                case PermissionHelper.MediaProjectionCode:
                    RequestScreenCapturePermissionResult(requestCode, resultCode, data);
                    break;
            }
        }
        /// <summary>
        /// 请求无障碍服务
        /// </summary>
        public bool RequestAccessbilityPermission(Context context, string serviceClassName)
        {
            if (!IsAccessibilityEnabled(context,serviceClassName)) 
            {
                var intent = new Intent(Settings.ActionAccessibilitySettings);
                intent.AddFlags(ActivityFlags.NewTask);
                _activity.StartActivity(intent);
            }
            return true;
        }
        public bool IsAccessibilityEnabled(Context context, string serviceClassName)
        {
            CommUtils.WriteLog("判断是否可用！");
            var accessibilityManager = (AccessibilityManager)context.GetSystemService(Context.AccessibilityService);
            var enabledServices = accessibilityManager.GetEnabledAccessibilityServiceList(FeedbackFlags.AllMask);
            CommUtils.WriteLog($"判断是否可用！{enabledServices.Count}");
            if (enabledServices!=null && enabledServices.Count > 0)
            {
                CommUtils.WriteLog($"判断是否可用??！{enabledServices[0].PackageNames}");
            }
            bool isEnable = enabledServices.Any(s=> {
                CommUtils.WriteLog($"服务名称：{s.ResolveInfo.ServiceInfo.Name}");
                return s.ResolveInfo.ServiceInfo.Name.Contains(serviceClassName);
            });
            string targetServiceId = $"{context.PackageName}/{serviceClassName}";
            return isEnable;
        }
    }
}
